<?php
if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );
require_once ('./application/controllers/authenticate.php');
class User extends Authenticate {
	
	function __construct() {
		parent::__construct ();
		$this->load->model ( 'admin_model' );
		$this->load->model ( 'role_model' );
		$this->load->library ( 'html/control/fx_control' );
		$this->load->library ( 'html/control/fx_filter' );
		$this->load->library ( 'html/control/fx_sort' );
		$this->admin_model->addAttributeOrder ( 'id', 'desc' );
		$this->load->library ( 'upload' );
	}
	
	protected function _eventLoadLayout() {
		$this->page ['title'] = 'User Management';
		$this->module ['title'] = 'User Management';
		$this->module ['grid'] ['records'] = 20;
		$this->module ['grid'] ['page_range'] = 5;
	}
	
	function index() {
		$data = $this->_initGridView ();
		$this->setPageContent ( 'system/user/grid', $data );
		$this->renderLayout ();
	}
	
	protected function _initGridView() {
		
		// Get Paginator Params
		$page = $this->input->getParam ( 'page' );
		$recordPerPage = $this->input->getParam ( 'recordPerPage' );
		if (! $recordPerPage) {
			$recordPerPage = $this->module ['grid'] ['records'];
		}
		
		// Get Filter Params
		$filters = $this->input->post ( 'userFilter' );
		// Filter
		$this->fx_filter->filter ( $filters, $this->admin_model );
		
		// Get Order Params
		$order = $this->input->post ( 'userOrder' );
		// Sort
		$this->fx_sort->sort ( $order, $this->admin_model );
		// Get total found records
		$found = $this->admin_model->countTotal ();
		
		// Paginate
		$this->load->library ( "tree/paginator/engine/st_paginator_collection" );
		$this->load->library ( "tree/paginator/st_paginator" );
		$this->st_paginator_collection->setModel ( $this->admin_model );
		$this->st_paginator->setConfig ( array ('engine' => $this->st_paginator_collection, 'pageRange' => $this->module ['grid'] ['page_range'], 'itemCountPerPage' => $recordPerPage, 'currentPageNumber' => $page ) );
		
		// Paginate Collection
		$collection = $this->st_paginator->getItemsByPage ( $page );
		if (empty ( $collection )) {
			$collection = array ();
		}
		$data = array ();
		$data ['found'] = $found;
		$data ['sorter'] = $this->fx_sort;
		$data ['filters'] = $this->fx_filter;
		$data ['paginator'] = $this->st_paginator;
		$data ['user_ids'] = $this->input->post ( 'user_ids' );
		$data ['user_ids_array'] = explode ( ',', $this->input->post ( 'user_ids' ) );
		$data ['collection'] = $collection;
		return $data;
	
	}
	
	public function edit() {
		try {
			$id = $this->input->getParam ( 'id' );
			$admin = new admin_model ();
			if ($id) {
				$admin->loadByPK ( $id );
			}
			$data ['model'] = $admin;
			$data ['roles'] = $this->role_model->getCollection ();
			$this->setPageContent ( 'system/user/edit', $data );
			$this->renderLayout ( 'layouts/ajax' );
		} catch ( Exception $ex ) {
			throw $ex;
		}
	}
	
	public function massActive() {
		try {
			// Load User Model
			$ids = $this->input->getMassValues ( 'user_ids' );
			if ($ids) {
				$this->admin_model->query ( "update admin_user set is_active = 1 where id in ($ids)" );
			}
			$countItem = count ( explode ( ',', $ids ) );
			$this->st_registry->register ( 'admin/system/user/message', "Active $countItem items successfully" );
			redirect ( site_url ( "admin/system/user/index", true ) );
		} catch ( Exception $ex ) {
			$this->st_registry->register ( 'admin/system/user/error', $e->getMessage () );
			redirect ( site_url ( "admin/system/user/index", true ) );
		}
	}
	
	public function massDeactive() {
		try {
			// Load User Model
			$ids = $this->input->getMassValues ( 'user_ids' );
			if ($ids) {
				$this->admin_model->query ( "update admin_user set is_active = 0 where id in ($ids)" );
			}
			$countItem = count ( explode ( ',', $ids ) );
			$this->st_registry->register ( 'admin/system/user/message', "Deactive $countItem items successfully" );
			redirect ( site_url ( "admin/system/user/index", true ) );
		} catch ( Exception $ex ) {
			$this->st_registry->register ( 'admin/system/user/error', $e->getMessage () );
			redirect ( site_url ( "admin/system/user/index", true ) );
		}
	}
	
	public function massSetRole() {
		try {
			// Load User Model
			$ids = $this->input->getMassValues ( 'user_ids' );
			$roleId = $this->input->post ( 'roleSetterId' );
			if ($ids && ( integer ) $roleId != 0) {
				$this->admin_model->query ( "update admin_user set role_id = $roleId where id in ($ids)" );
			}
			$countItem = count ( explode ( ',', $ids ) );
			$this->st_registry->register ( 'admin/system/user/message', "Update $countItem items successfully" );
			redirect ( site_url ( "admin/system/user/index", true ) );
		} catch ( Exception $ex ) {
			$this->st_registry->register ( 'admin/system/user/message', $e->getMessage () );
			redirect ( site_url ( "admin/system/chapter/index", true ) );
		}
	}
	
	public function save() {
		try {
			//print_r ($this->input->post('user'));
			// Load User Model
			$admin = new admin_model ();
			$id = $this->input->post ( 'id' );
			if ($id) {
				$admin->loadByPK ( $id );
			} else {
				$admin->setCreatedAt ( "NOW()" );
			}
			$data = $this->input->post ( 'user' );
			if (is_array ( $data ) && count ( $data ) > 0) {
				//Upload Thumb Image
				$config ['upload_path'] = './media/admin/avatars/';
				$config ['allowed_types'] = 'gif|jpg|png|bmp';
				$config ['max_size'] = '500';
				$this->upload->initialize ( $config );
				$this->upload->do_upload ( 'user_avatar' );
				$dataUpload = $this->upload->data ();
				$avatarPath = $config ['upload_path'] . $dataUpload ['file_name'];
				if (strlen ( $dataUpload ['file_name'] ) > 0) {
					$admin->setAvatar ( $avatarPath );
				}
				if (md5 ( $data ['password'] ) == $admin->getPassword ()) {
					unset ( $data ['password'] );
				} else {
					$data ['password'] = md5 ( $data ['password'] );
				}
				unset ( $data ['is_expired'] );
				$admin->setEntireData ( $data );
				$admin->setUpdatedAt ( "NOW()" );
				$admin->save ();
			}
			redirect ( site_url ( "admin/system/user/index", true));
		} catch ( Exception $ex ) {
			echo $ex->getMessage ();
		}
	}
	
	public function delete() {
		try {
			$id = $this->input->getParam ( 'id' );
			if (! $id) {
				redirect ( site_url ( "admin/system/user/index", true ) );
			}
			$admin = new admin_model ();
			$admin->loadByPK ( $id );
			if ($admin->isLoaded ()) {
				$name = $admin->getUsername ();
				$admin->delete ();
				$this->st_registry->register ( 'admin/system/user/message', "Delete user [$name] successfully" );
				redirect ( site_url ( "admin/system/user/index", true ) );
			} else {
				$this->st_registry->register ( 'admin/system/user/message', "Cannot delete user" );
				redirect ( site_url ( "admin/system/user/index", true ) );
			}
		} catch ( Exception $ex ) {
			$this->st_registry->register ( 'admin/system/user/error', "Error when deleting user" );
			redirect ( site_url ( "admin/system/user/index", true ) );
		}
	}
}